<template>
  <div id="addQuestion">
    <h2 style="text-align: center; padding-left: 4%">{{ title }}</h2>
    <div class="container">
      <a-form :model="form" @submit="handleSubmit">
        <a-form-item field="title" label="标题">
          <a-input v-model="form.title" placeholder="请输入标题" />
        </a-form-item>
        <a-form-item field="tags" label="标签" tooltip="输入之后请按回车">
          <a-input-tag
            v-model="form.tags"
            placeholder="请输入标签"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="content" label="内容">
          <MdEditor
            :value="form.content"
            :handleChange="onChangeContent"
          ></MdEditor>
        </a-form-item>
        <a-form-item field="answer" label="答案">
          <MdEditor
            :value="form.answer"
            :handleChange="onChangeAnswer"
          ></MdEditor>
        </a-form-item>
        <a-form-item field="judgeConfig.memoryLimit" label="内存限制">
          <a-input
            v-model="form.judgeConfig.memoryLimit"
            placeholder="请输入内存限制（kb）"
          />
        </a-form-item>
        <a-form-item field="judgeConfig.stackLimit" label="堆栈限制">
          <a-input
            v-model="form.judgeConfig.stackLimit"
            placeholder="请输入堆栈限制（kb）"
          />
        </a-form-item>
        <a-form-item field="judgeConfig.timeLimit" label="时间限制">
          <a-input
            v-model="form.judgeConfig.timeLimit"
            placeholder="请输入时间限制（ms）"
          />
        </a-form-item>
        <a-form-item
          v-for="(item, index) of form.judgeCase"
          :label="`测试用例${index + 1}`"
          :key="index"
        >
          <a-space>
            <a-input v-model="item.input" placeholder="输入用例" />
            <a-input v-model="item.output" placeholder="输出用例" />
            <a-button @click="caseDelete(index)" status="danger">删除</a-button>
          </a-space>
        </a-form-item>
        <div class="addBtn">
          <a-button @click="caseAdd" status="success">新增用例</a-button>
          <a-button html-type="submit" type="primary" style="width: 220px"
            >提交
          </a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import message from "@arco-design/web-vue/es/message";
import { QuestionControllerService } from "../../../generated";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");
const title = updatePage ? "修改题目" : "创建题目";
/**
 * 初始化值
 */
let form = ref({
  title: "",
  tags: [],
  answer: "",
  content: "",
  judgeConfig: {
    memoryLimit: "",
    stackLimit: "",
    timeLimit: "",
  },
  judgeCase: [
    {
      input: "",
      output: "",
    },
  ],
});

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const res = await QuestionControllerService.getQuestionByIdUsingGet(
    id as any
  );
  if (res.code === 0) {
    form.value = res.data as any;
    // json 转 js 对象
    if (!form.value.judgeCase) {
      form.value.judgeCase = [
        {
          input: "",
          output: "",
        },
      ];
    } else {
      form.value.judgeCase = JSON.parse(form.value.judgeCase as any);
    }
    if (!form.value.judgeConfig) {
      form.value.judgeConfig = {
        memoryLimit: "",
        stackLimit: "",
        timeLimit: "",
      };
    } else {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig as any);
    }
    if (!form.value.tags) {
      form.value.tags = [];
    } else {
      form.value.tags = JSON.parse(form.value.tags as any);
    }
  } else {
    message.error("加载失败，" + res.message);
  }
};

onMounted(() => {
  loadData();
});

/**
 * 改变context的值
 * @param v
 */
const onChangeContent = (v: string) => {
  form.value.content = v;
};

/**
 * 改变answer的值
 * @param v
 */
const onChangeAnswer = (v: string) => {
  form.value.answer = v;
};

/**
 * 新增用例
 */
const caseAdd = () => {
  form.value.judgeCase.push({
    input: "",
    output: "",
  });
};

/**
 * 删除用例
 * @param index
 */
const caseDelete = (index: number) => {
  if (form.value.judgeCase.length == 1) {
    message.error("至少要有一个测试用例");
    return;
  }
  form.value.judgeCase.splice(index, 1);
};

/**
 * 提交
 */
const handleSubmit = async () => {
  if (updatePage) {
    const res = await QuestionControllerService.updateQuestionUsingPost(
      form.value as any
    );
    if (res.code === 0) {
      message.success("更新成功");
      router.push({
        path: "/manage/question",
        replace: true,
      });
    } else {
      message.error("更新失败，" + res.message);
    }
  } else {
    const res = await QuestionControllerService.addQuestionUsingPost(
      form.value as any
    );
    if (res.code === 0) {
      message.success("创建成功");
      form.value = {
        title: "",
        tags: [],
        answer: "",
        content: "",
        judgeConfig: {
          memoryLimit: "",
          stackLimit: "",
          timeLimit: "",
        },
        judgeCase: [
          {
            input: "",
            output: "",
          },
        ],
      };
    } else {
      message.error("创建失败，" + res.message);
    }
  }
};
</script>
<style scoped>
.container {
  padding: 0 20% 1% 10%;
}

.addBtn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 11%;
}
</style>
